package com.hugang.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 带版本号的原子引用
 *
 * @author hg
 * @date 2020/8/24 19:56
 */
public class AtomicStampReferenceDemo {

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Integer> atomicReference = new AtomicReference<>(100);
        AtomicStampedReference<Integer> stampedReference = new AtomicStampedReference<Integer>(100, 1);
        System.out.println("=============使用AtomicReference不能解决ABA问题============");
        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "t1").start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                //若修改成功则表示存在ABA问题未解决
                System.out.println(Thread.currentThread().getName() + " ---> " + atomicReference.compareAndSet(100, 2019) + "  " + atomicReference.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();

        TimeUnit.SECONDS.sleep(2);
        System.out.println("=============使用AtomicStampedReference解决ABA问题============");
        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " ---> 第一次版本号为：" + stampedReference.getStamp());
                TimeUnit.SECONDS.sleep(1);
                //修改一次，版本号+1
                stampedReference.compareAndSet(100, 101, stampedReference.getStamp(), stampedReference.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + " ---> 修改一次之后的版本号为：" + stampedReference.getStamp());
                stampedReference.compareAndSet(101, 100, stampedReference.getStamp(), stampedReference.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + " ---> 修改两次之后的版本号为：" + stampedReference.getStamp());


            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t3").start();
        new Thread(() -> {
            try {
                int stamp = stampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + " ---> 第一次版本号为：" + stamp);
                TimeUnit.SECONDS.sleep(2);
                //类似于乐观锁，根据版本号进行修改，若当前版本和期望版本不一致，则说明此值被修改过，因此不能进行修改。返回false代表解决ABA问题
                boolean b = stampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
                System.out.println(Thread.currentThread().getName() + " ---> " + b + "  " + stampedReference.getReference());



            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t4").start();
    }
}
